/* eslint-disable no-irregular-whitespace */
<template>
  <div class="pageWrapper">
    <SearchBar @onSearch="handleSearch" @childFn="resetForm">
      <SearchBarItem label="机构名称：" :labelLg="8">
        <Input type="text" v-model="dataModule.organizationName" placeholder="请输入机构名称" clearable/>
      </SearchBarItem>
      <SearchBarItem label="商户名称：" :labelLg="8">
        <Input type="text" v-model="dataModule.merchantName" placeholder="请输入商户名称" clearable/>
      </SearchBarItem>
      <SearchBarItem label="支付渠道：" :labelLg="8">
        <Select v-model="dataModule.paymentChannelCode" placeholder="请选择支付渠道" clearable>
          <Option v-for="(item, index) in selectChannel" :key="item + index" :value="item.key">{{ item.value }}</Option>
        </Select>
      </SearchBarItem>
      <SearchBarItem label="开户名：" :labelLg="8">
        <Input type="text" v-model="dataModule.accountName" placeholder="请输入开户名" clearable/>
      </SearchBarItem>
      <SearchBarItem label="账号：" :labelLg="8">
        <Input type="text" v-model="dataModule.accountNo" placeholder="请输入账号" clearable/>
      </SearchBarItem>
      <SearchBarItem label="城市：" :labelLg="8">
        <Cascader :data="cityList" :load-data="cityLoadData" :clearable="false" v-model="city" @on-change="getCityName"
                  ref="address"></Cascader>
      </SearchBarItem>
      <SearchBarItem label="创建时间：" :labelLg="8">
        <DatePicker type="date" v-model="dataModule.createdDt" ref="createDatePicker" :options="timeOptions"
                    format="yyyy-MM-dd" @on-change="changeCreated" placeholder="创建时间"></DatePicker>
      </SearchBarItem>
      <SearchBarItem label="商户编号：" :labelLg="8">
        <Input type="text" v-model="dataModule.merchantCode" placeholder="请输入商户号" clearable/>
      </SearchBarItem>

    </SearchBar>
    <RemoteTable :namespace="namespace" :columns="columns" @onSortChange="onSortChange" ref="tableData">
      <template #extra>
        <Authc permissions="trade:merchant:commercial:edit">
          <Button type="primary" @click="handleClick('add', 'dataModule')">新增</Button>
        </Authc>
        <Authc permissions="trade:merchant:commercial:export">
          <Button type="primary" @click="exportExcel">导出</Button>
        </Authc>
      </template>
    </RemoteTable>
  </div>
</template>

<script>
import Loading from '@/components/Loading';
import RemoteTable from '@/components/RemoteTable';
import RemoteSelect from '@/components/RemoteSelect';
import SearchBar from '@/components/SearchBar';
import {namespace} from '../module/commercial';
import Authc from '@/components/Authc';
import Action from './Action';
import config from '@/utils/config';
import appService from '@/utils/appService';
import util from '@/utils/util';
import { Modal } from "view-design";

const settlement_type_list=[{key:'1',value:'清分'},{key:'2',value:'自营'},{key:'3',value:'平台'}]
export default {
  name: 'tables_page',
  components: {
    Loading,
    RemoteTable,
    SearchBar,
    SearchBarItem: SearchBar.SearchBarItem,
    RemoteSelect,
    Authc,
    Action,
  },
  activated() {
    // console.log('重新激活了');
  },
  data() {
    let this_this = this;

    return {
      namespace: namespace,
      loading: true,
      dataModule: {},
      oNameSelect: [], // 机构名称
      selectChannel: [], // 渠道
      selectAccount: [], // 结算账户类型
      selectScenario: [], // 业务场景
      columns: [
        {
          title: '序号',
          type: 'index',
          width: 80,
          align: 'center'
          // fixed: "left"
        },
        {
          title: '机构名称',
          key: 'organizationName',
          minWidth: 210,
          align: 'center'
          // fixed: "left"
        },
        {
          title: '商户编码',
          key: 'merchantCode',
          minWidth: 300,
          align: 'center'
        },
        {
          title: '商户名称',
          key: 'merchantName',
          minWidth: 210,
          align: 'center'
        },
        {
          title: '收入类型',
          key: 'revenueTypeName',
          minWidth: 150,
          align: 'center'
        },
        // {
        //   title: '开户行',
        //   key: 'openingBank',
        //   minWidth: 150,
        //   align: 'center'
        // },
        // {
        //   title: '开户名',
        //   key: 'accountName',
        //   minWidth: 150,
        //   align: 'center'
        // },
        // {
        //   title: '结算账户类型',
        //   key: 'accountTypeName',
        //   minWidth: 130,
        //   align: 'center'
        // },
        {
          title: '结算类型',
          key: 'settlementType',
          minWidth: 150,
          align: 'center',
          render: function (h, data) {
            const select= settlement_type_list.filter(item=>item.key===data.row.settlementType)
            debugger
            if(select && select.length){
              return h("label", select[0].value);
            }
            return h("label", '无');
          }
        },
        {
          title: '场景',
          key: 'scene',
          minWidth: 150,
          align: 'center',
          render: function (h, data) {
            if (data.row.scene === undefined || data.row.scene == null || data.row.scene === "" || data.row.scene.length < 1) {
              return h("label", "");
            } else {
              let sceneArr = data.row.scene.split(",");
              let sceneMap = new Map();
              this_this.selectScenario.forEach(sc => {
                sceneMap.set(sc.key, sc.value)
              });
              return h("ul", sceneArr.map(item => {
                return h("label", {style: {marginRight: '5px'}}, sceneMap.get(item))
              }));
            }
          }
        },
        // {
        //   title: '城市',
        //   key: 'cityName',
        //   minWidth: 150,
        //   align: 'center'
        // },
        {
          title: '创建时间',
          key: 'createdDt',
          minWidth: 150,
          align: 'center'
        },
        // {
        //   title: '备注',
        //   key: 'remark',
        //   minWidth: 150,
        //   align: 'center',
        //   render: (h, params) => {
        //     return h('div', [h('span', {
        //       style: {
        //         display: 'inline-block',
        //         width: '100%',
        //         overflow: 'hidden',
        //         textOverflow: 'ellipsis',
        //         whiteSpace: 'nowrap'
        //       },
        //       domProps: {title: params.row.describe},
        //       on: {
        //         click: (e) => {
        //           e.stopPropagation();
        //         }
        //       }
        //     }, params.row.remark)]);
        //   },
        // },
        {
          title: '操作',
          key: 'action',
          // fixed: "right",
          align: 'center',
          permissions: ['trade:merchant:commercial'],
          width: 180,
          render: function (h, data) {
            return h(Action, {
              props: {
                row: data.row
              }
            });
          }
        }
      ],
      city: [],
      dataList: [],
      cityList: [],
      timeOptions: {
        disabledDate: date => {
          return date && date.valueOf() > Date.now();
        }
      }
    };
  },
  created() {
    /** 如果 url 没有带参数，就重置请求参数 **/
    this.$store.commit(`${namespace}/reviseQuery`);
    let merchantCode = this.$route.query.merchantCode;
    if(merchantCode){
      this.dataModule.merchantCode=merchantCode
    }
    this.getSelect();
    this.getCity();
  },
  methods: {
    changeCreated(e) {
      this.dataModule.createdDt = e;
    },
    getCityName(item, selectedData) {
      if (item.length == 2) {
        this.dataModule.cityCode = item ? item[1] : '';
        this.city = [item[1]];
      } else if (item.length == 1) {
        this.dataModule.cityCode = item ? item[0] : '';
        this.city = [item[0]];
      }
    },
    /** 导出 */
    async exportExcel() {
      try {
        let res = await this.$store.dispatch(
            `${namespace}/exportExcel`,
            this.dataModule
        );
        let link = document.createElement('a');

        util.exportExcle(res, '商户管理表');
      } catch (error) {
        this.$Message.error({
          content: '导出失败'
        });
      }
    },
    // 清空事件；
    resetForm() {
      let path = this.$route.path; //先获取路由路径
      this.$router.push(path)
    },
    // 组织机构下拉
    getInstitutionName() {
      this.$store
          .dispatch(`${namespace}/getInstitutionName`)
          .then(res => {
            if (res.data.errorCode === 0) {
              let data = res.data.data.list.map(
                  ({organizationCode, organizationName}) => {
                    return {
                      label: organizationName,
                      value: organizationCode
                    };
                  }
              );
              this.oNameSelect = data;
            }
          });
    },
    searchTime(date, type) {
      this.dataModule.contractStartDate = date ? date[0] : '';
      this.dataModule.contractEndDate = date ? date[1] : '';
    },
    // 城市
    getCity() {
      let params = {
        pid: 1
      };
      this.$store
          .dispatch(`${namespace}/getCityData`, params)
          .then(res => {
            this.cityList = res.data.data ? res.data.data.map(
                ({name, pid, adcode, id}) => {
                  if (
                      [
                        '北京',
                        '天津',
                        '上海',
                        '重庆',
                        '澳门',
                        '香港'
                      ].includes(name)
                  ) {
                    return {
                      label: name,
                      value: id
                    };
                  } else {
                    return {
                      label: name,
                      value: id,
                      children: [],
                      loading: false
                    };
                  }
                }
            ) : [];
          });
    },
    /** 城市市级区域 */
    async cityLoadData(item, callback) {
      try {
        let id = {
          pid: item.value
        };
        item.loading = true;
        let res = await this.$store.dispatch(
            `${namespace}/getCityData`,
            id
        );
        if (res.data.ret == 0) {
          item.children = res.data.data.map(
              ({name, pid, adcode, id}) => {
                return {
                  label: name,
                  value: id
                };
              }
          );
          item.loading = false;
          callback();
        }
      } catch (error) {
        this.$Message.error({
          content: error
        });
      }
    },
    // 字典
    getSelect() {
      this.$store
          .dispatch(`${namespace}/getMerchantSearchKey`)
          .then(res => {
            if (res.data.errorCode === 0) {
              let data = res.data.data;
              this.selectChannel = data.merchantPaymentChannel; // 渠道
              this.selectScenario = data.merchantScenario; // 场景
              this.selectAccount = data.merchantAccountType; // 结算账户类型
            }
          });
    },
    // 新增
    handleClick(type) {
      switch (type) {
        case 'add':
          this.$router.push('AddCommercialDetailFrom');
          break;
        case 'edit':
          break;
        case 'delete':
          break;
        default:
      }
    },
    async handleSearch() {
      try {
        let pageSize = {
          currentPage: 1,
          pageSize: 10
        };
        let merchantCode = this.$route.query.merchantCode;
        if(merchantCode){
          this.dataModule.merchantCode=merchantCode
        }
        let sceneList = this.dataModule.scene;
        if (this.dataModule.scene != null && (typeof this.dataModule.scene === "object")) {
          this.dataModule.scene = this.dataModule.scene.join(',');
        }
        await this.$store.dispatch(`${namespace}/query`, {...this.dataModule, ...pageSize});
        this.dataModule.scene = sceneList;
      } catch (error) {
        this.$Message.error({
          content: error
        });
      }
    },
    onSortChange(sort) {
      if (sort.order === 'normal') {
        this.queryParam.order = [];
      } else {
        this.queryParam.order = [sort.key + ' ' + sort.order];
      }
      this.handleSearch();
    }
    // resetForm() {
    //   this.$refs["formArea"].resetFields();
    // }
  },
  async mounted() {
    this.$bus.$on('actionType', data => {
      let id = data.id;
      if (data.type === 'edit') {
      } else if (data.type === 'delete') {
        Modal.confirm({
          render: (h, params) => {
            return h('div', [
              h('div', {
                style: 'margin-bottom:10px;vertical-align: middle;font-size: 16px;color: #17233d;font-weight: 700;'
              }, '提示'),
              h(
                  'div',
                  {
                    class: 'selfConfirm'
                  },
                  '确定删除?'
              )
            ]);
          },
          onOk: () => {
            return this.$store
                .dispatch(`${namespace}/delete`, id)
                .then(res => {
                  if (res.errorCode === 0) {
                    this.$Message.success(res.msg);
                    this.$store.dispatch(`${namespace}/query`);
                  } else {
                    this.$Message.warning(res.msg);
                  }
                });
          }
        });
      }
    });
  },
  beforeDestroy() {
    this.$bus.$off('actionType');
  }
};
</script>
